const baseUrl = "192.168.0.110";
const imgUrl = "http://" + baseUrl + "/file/img/download?imgName=";

//封装一个ajax的请求方法
const ajax = params => {

  //调用等待框
  wx.showLoading({
    title: '请求中...',
  })

  //设置一个请求对象
  var requestObj = {};
  requestObj.url = "http://" + baseUrl + params.url;
  // requestObj.url = "http://10.36.100.180" + params.url;
  requestObj.data = params.data ? params.data : {};
  requestObj.method = params.type ? params.type : "GET";
  requestObj.header = {"content-type": "application/x-www-form-urlencoded"};

  //获取登录的令牌
  var loginToken = wx.getStorageSync('loginToken');
  if(loginToken){
    requestObj.header.loginToken = loginToken;
  }
  requestObj.header.fromType = 2;

  requestObj.success = (data) => {
    var status = data.statusCode;
    //请求结果
    var result = data.data;
    if(status == 200) {
      //调用外界的成功响应的方法
      if(params.success){
        params.success(result.data);
      }
    } else if (result.code == 406){
      //处理没有登录的情况

      //认证失败
      wx.removeStorageSync('loginToken');
      wx.removeStorageSync('header');
      wx.removeStorageSync('nickname');

      // //请求失败
      // wx.showToast({
      //   title: result.msg ? result.msg : "服务器异常请稍后再试...",
      //   icon: "error"
      // });

      //重新发送登录请求
      login({
        header: "",
        nickname: "",
        success: () => {
          //重新发送抢红包的请求
          ajax(params);
        }
      });

    } else {
      //请求失败
      wx.showToast({
        title: result.msg ? result.msg : "服务器异常请稍后再试...",
        icon: "error"
      });
    }

    //关闭等待框
    wx.hideLoading();
  };

  wx.request(requestObj);
}

/**
 * 进行小程序端的登录
 */
const login = obj =>{
  wx.login({
    success: (data) => {
      //将code传递给后端
      ajax({
        type: "POST",
        url: "/auth/sys/login",
        data: {
          wxCode: data.code,
          header: obj.header,
          nickname: obj.nickname,
          fromType: 2
        },
        success: (data) => {
          //获取登录令牌
          wx.showToast({
            title: "登录成功",
            icon: "success"
          });

          //保存到本地中 - 登录令牌
          wx.setStorageSync("loginToken", data);
          wx.setStorageSync("header", obj.header);
          wx.setStorageSync("nickname", obj.nickname);

          //调用登录成功的回调方法
          if(obj.success){
            obj.success();
          }
        }
      });
    }
  });
}

module.exports = {
  ajax,
  login,
  baseUrl,
  imgUrl
}
